import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { localCache } from '@/utils'
import { firstMenu } from '@/utils/map-menus'
import store from '@/store'
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('@/views/main/main.vue')
    //  根据userMenus来决定的
  },
  {
    path: '/:pathMatch(.*)*',
    component: () => import('@/views/not-found/not-found.vue')
  }
]
const router = createRouter({
  routes,
  history: createWebHashHistory()
})

// 路由前置守卫
router.beforeEach((to: any, from) => {
  const token = localCache.getCache('token')
  if (to.path !== '/login') {
    if (!token) {
      // 清除localstoreage的缓存
      store.dispatch('login/clearLocalLogin')
      ElMessage.warning('请重新登录')
      store.commit('login/SET_PATH', to.path)
      return {
        path: '/login',
        query: {
          path: to.path
        }
      }
    }
    const redirect = (store.state as any).login.path
    if (redirect && token) {
      // 实现token过期登录过后跳转至过期前的页面
      store.commit('login/SET_PATH', '')
      return redirect
    }
    if (to.path === '/main') {
      // 实现第二次重定向，第一次路由重定向会跳转之main 我们需要匹配一下第一个菜单路径使路由定向到第一个菜单位置
      return firstMenu.url
    }
  } else {
    if (token && to.path === '/login') {
      // 禁止有token 并且还想去login
      return '/main'
    }
  }
})
export default router
